<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="logo">
          <img src="/favicon.ico" alt="Logo" />
          <h1>Admin2025</h1>
        </div>
        <p class="subtitle">欢迎回来，请登录您的账户</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <div class="form-options">
            <el-checkbox v-model="loginForm.remember">
              记住我
            </el-checkbox>
            <el-link type="primary" @click="showForgotPassword">
              忘记密码？
            </el-link>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>还没有账户？ <el-link type="primary" @click="showRegister">立即注册</el-link></p>
      </div>
    </div>
    
    <!-- 注册对话框 -->
    <el-dialog
      v-model="registerVisible"
      title="用户注册"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="registerVisible = false">取消</el-button>
          <el-button type="primary" :loading="registerLoading" @click="handleRegister">
            注册
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="重置密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="forgotPasswordFormRef"
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
        label-width="80px"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="forgotPasswordForm.email" placeholder="请输入注册邮箱" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="forgotPasswordVisible = false">取消</el-button>
          <el-button type="primary" :loading="resetPasswordLoading" @click="handleResetPassword">
            发送重置邮件
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAuth } from '@/composables/useAuth'
import { rules } from '@/utils/validation'

export default {
  name: 'LoginView',
  components: {
    User,
    Lock
  },
  setup() {
    const { login, register, resetPassword, getRememberedUsername } = useAuth()
    
    const loginFormRef = ref(null)
    const registerFormRef = ref(null)
    const forgotPasswordFormRef = ref(null)
    
    const loading = ref(false)
    const registerLoading = ref(false)
    const resetPasswordLoading = ref(false)
    
    const registerVisible = ref(false)
    const forgotPasswordVisible = ref(false)
    
    // 登录表单
    const loginForm = reactive({
      username: '',
      password: '',
      remember: false
    })
    
    // 注册表单
    const registerForm = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    })
    
    // 忘记密码表单
    const forgotPasswordForm = reactive({
      email: ''
    })
    
    // 登录验证规则
    const loginRules = {
      username: [rules.required('请输入用户名')],
      password: [rules.required('请输入密码')]
    }
    
    // 注册验证规则
    const registerRules = {
      username: [
        rules.required('请输入用户名'),
        rules.username('用户名格式不正确')
      ],
      email: [
        rules.required('请输入邮箱'),
        rules.email('邮箱格式不正确')
      ],
      password: [
        rules.required('请输入密码'),
        rules.password('密码长度应为6-20位')
      ],
      confirmPassword: [
        rules.required('请确认密码'),
        {
          validator: (rule, value, callback) => {
            if (value !== registerForm.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 忘记密码验证规则
    const forgotPasswordRules = {
      email: [
        rules.required('请输入邮箱'),
        rules.email('邮箱格式不正确')
      ]
    }
    
    // 登录处理
    const handleLogin = async () => {
      try {
        await loginFormRef.value.validate()
        loading.value = true
        await login(loginForm)
      } catch (error) {
        console.error('Login validation failed:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 注册处理
    const handleRegister = async () => {
      try {
        await registerFormRef.value.validate()
        registerLoading.value = true
        
        const result = await register(registerForm)
        if (result.success) {
          registerVisible.value = false
          // 清空表单
          Object.keys(registerForm).forEach(key => {
            registerForm[key] = ''
          })
          registerFormRef.value.resetFields()
        }
      } catch (error) {
        console.error('Register validation failed:', error)
      } finally {
        registerLoading.value = false
      }
    }
    
    // 重置密码处理
    const handleResetPassword = async () => {
      try {
        await forgotPasswordFormRef.value.validate()
        resetPasswordLoading.value = true
        
        const result = await resetPassword(forgotPasswordForm)
        if (result.success) {
          forgotPasswordVisible.value = false
          forgotPasswordForm.email = ''
          forgotPasswordFormRef.value.resetFields()
        }
      } catch (error) {
        console.error('Reset password validation failed:', error)
      } finally {
        resetPasswordLoading.value = false
      }
    }
    
    // 显示注册对话框
    const showRegister = () => {
      registerVisible.value = true
    }
    
    // 显示忘记密码对话框
    const showForgotPassword = () => {
      forgotPasswordVisible.value = true
    }
    
    // 初始化
    onMounted(() => {
      // 填充记住的用户名
      const rememberedUsername = getRememberedUsername()
      if (rememberedUsername) {
        loginForm.username = rememberedUsername
        loginForm.remember = true
      }
    })
    
    return {
      // refs
      loginFormRef,
      registerFormRef,
      forgotPasswordFormRef,
      
      // 状态
      loading,
      registerLoading,
      resetPasswordLoading,
      registerVisible,
      forgotPasswordVisible,
      
      // 表单数据
      loginForm,
      registerForm,
      forgotPasswordForm,
      
      // 验证规则
      loginRules,
      registerRules,
      forgotPasswordRules,
      
      // 方法
      handleLogin,
      handleRegister,
      handleResetPassword,
      showRegister,
      showForgotPassword
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 16px;
  padding: 40px 32px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 16px;
}

.logo img {
  width: 48px;
  height: 48px;
}

.logo h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 24px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.login-footer {
  text-align: center;
  color: #666;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  height: 48px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

@media (max-width: 480px) {
  .login-box {
    padding: 32px 24px;
    margin: 20px;
  }
  
  .logo h1 {
    font-size: 24px;
  }
}
</style>
